package controllers

import (
	"net/http"
	"strconv"

	"gitee.com/kun_liu/to-log/app/models"
	"gitee.com/kun_liu/to-log/app/services"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

// APIController API控制器
type APIController struct {
	postService     *services.PostService
	categoryService *services.CategoryService
	tagService      *services.TagService
	commentService  *services.CommentService
	userService     *services.UserService
}

// NewAPIController 创建API控制器实例
func NewAPIController() *APIController {
	return &APIController{
		postService:     services.NewPostService(),
		categoryService: services.NewCategoryService(),
		tagService:      services.NewTagService(),
		commentService:  services.NewCommentService(),
		userService:     services.NewUserService(),
	}
}

// GetPosts 获取文章列表
func (c *APIController) GetPosts(ctx *gin.Context) {
	// 获取分页参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10"))

	// 获取文章列表
	posts, total, err := c.postService.GetPosts(page, pageSize)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "获取文章列表失败",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"success": true,
		"data": gin.H{
			"posts":      posts,
			"total":      total,
			"page":       page,
			"page_size":  pageSize,
			"total_page": (total + int64(pageSize) - 1) / int64(pageSize),
		},
	})
}

// GetPost 获取文章详情
func (c *APIController) GetPost(ctx *gin.Context) {
	// 获取文章ID
	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "无效的文章ID",
		})
		return
	}

	// 获取文章信息
	post, err := c.postService.GetPostByID(uint(id))
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{
			"success": false,
			"message": "文章不存在",
		})
		return
	}

	// 获取文章评论
	comments, _, err := c.commentService.GetCommentsByContentID(post.ID, 1, 100)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "获取评论失败",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"success": true,
		"data": gin.H{
			"post":     post,
			"comments": comments,
		},
	})
}

// GetCategories 获取分类列表
func (c *APIController) GetCategories(ctx *gin.Context) {
	// 获取分类列表
	categories, err := c.categoryService.GetCategories()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "获取分类列表失败",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"success": true,
		"data":    categories,
	})
}

// GetTags 获取标签列表
func (c *APIController) GetTags(ctx *gin.Context) {
	// 获取标签列表
	tags, err := c.tagService.GetTags()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "获取标签列表失败",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"success": true,
		"data":    tags,
	})
}

// CreateComment 创建评论
func (c *APIController) CreateComment(ctx *gin.Context) {
	var comment models.Comment
	if err := ctx.ShouldBindJSON(&comment); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数错误",
		})
		return
	}

	// 设置评论IP和UserAgent
	comment.IP = ctx.ClientIP()
	comment.Agent = ctx.GetHeader("User-Agent")

	// 创建评论
	err := c.commentService.CreateComment(&comment)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "评论失败",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "评论成功",
		"data":    comment,
	})
}

// Login 用户登录
func (c *APIController) Login(ctx *gin.Context) {
	// 获取登录参数
	type LoginForm struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}

	var form LoginForm
	if err := ctx.ShouldBindJSON(&form); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数错误",
		})
		return
	}

	// 验证用户名和密码
	user, err := c.userService.Login(form.Username, form.Password)
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"success": false,
			"message": "用户名或密码错误",
		})
		return
	}

	// 设置会话
	session := sessions.Default(ctx)
	session.Set("user_id", user.ID)
	session.Save()

	// 生成Token
	token := "token_placeholder" // 实际项目中应使用JWT等方式生成token

	ctx.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "登录成功",
		"data": gin.H{
			"token": token,
			"user":  user,
		},
	})
}
